package com.yong.sbd.biz.file.service.impl;

import com.yong.sbd.biz.file.config.properties.FileStorageProperties;
import com.yong.sbd.biz.file.service.FileService;
import com.yong.sbd.common.beans.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 文件处理
 *
 * @author Kang Yong
 * @date 2025/10/24
 * @since 1.0.0
 */
@Service
@AllArgsConstructor
public class FileServiceImpl implements FileService {

    private final FileStorageProperties fileStorageProperties;

    /**
     * 文件上传
     * <p>
     * 上传到当前日期命名的指定文件夹下，如果不存在创建文件夹
     * 文件名为当前时间戳
     *
     * @param file {@link MultipartFile}
     * @return {@link String}
     * @author Kang Yong
     * @date 2025/10/24
     */
    @Override
    public String upload(MultipartFile file) {
        try {
            // 文件夹
            String dataFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String basePath = fileStorageProperties.getLocation() + File.separator + dataFolder;
            Path path = Paths.get(basePath);
            if (!Files.exists(path)) {
                Files.createDirectories(path);
            }

            // 文件
            String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + file.getOriginalFilename();
            Files.copy(file.getInputStream(), path.resolve(fileName));

            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
    }

    @Override
    public void download(String filePath, String dataFolder, HttpServletRequest request, HttpServletResponse response) {
        try {
            // 文件是否存在
            String fileFullPath = fileStorageProperties.getLocation() + File.separator + dataFolder + File.separator + filePath;
            File file = new File(fileFullPath);
            if (!file.exists()) {
                throw new BusinessException("文件不存在");
            }

            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
            Files.copy(file.toPath(), response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
    }

}
